package com.db.jdbc;

import com.bean.Comment;
import com.bean.PaginationSupport;
import com.bean.Post;
import com.bean.User;
import com.db.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class JdbcCommentRepository implements CommentRepository {

    private JdbcTemplate jdbc;

    @Autowired
    public JdbcCommentRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }


    private static final String SELECT_COMMENT = "select comment.level,comment.post," +
                                                 " user.userID,user.userName,comment.content,comment.commentTime " +
                                                 " from comment,user where comment.poster = user.userID ";

    private static final String INSERT_COMMENT = "insert into comment values (? , ? , ? , ? , ?)";

    private static final String SELECT_PAGE_COMMENT = SELECT_COMMENT + " and post = ? order by level  limit ? offset ?";


    private static class commentRowMapper implements RowMapper<Comment> {
        public Comment mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new Comment(rs.getInt("comment.level"), new Post(rs.getInt("comment.post")),
                    new User(rs.getInt("user.userID"),rs.getString("user.userName")), rs.getString("comment.content"),
                    rs.getTimestamp("comment.commentTime"));
        }
    }

    @Override
    public Comment save(Comment comment) {
        jdbc.update(INSERT_COMMENT,comment.getLevel(),comment.getPost().getPostID(),comment.getPoster().getUserID(),
                                    comment.getContent(),comment.getCommentTime());
        return comment;
    }

    @Override
    public List<Comment> findByPost(Post post) {
        List<Comment> items = jdbc.query(SELECT_COMMENT + " and post = ? ",new commentRowMapper(),post.getPostID());

        return items;
    }

    @Override
    public PaginationSupport<Comment> findCommentPage(Post post,int pageNo, int pageSize) {
        int totalCount = findByPost(post).size();
        int startIndex = PaginationSupport.convertFromPageToStartIndex(pageNo, pageSize);
        if (totalCount < 1)
            return new PaginationSupport<Comment>(new ArrayList<Comment>(0), 0);

        List<Comment> items = jdbc.query(SELECT_PAGE_COMMENT , new commentRowMapper(),post.getPostID(), pageSize, startIndex);
        PaginationSupport<Comment> ps = new PaginationSupport<Comment>(items, totalCount, pageSize, startIndex);
        return ps;
    }
}
